<template>
  <view 
    class="chart-container" 
    ref="chartContainer" 
    style="position: relative; width: 100%; height: 500px; overflow: visible;">
    <canvas 
      :canvas-id="`rainAndFlowChart-${type}`" 
      :id="`rainAndFlowChart-${type}`"
      class="chart-canvas"
      :style="{ width: '100%', height: '100%' }"
      ></canvas>
  </view>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, watch, shallowRef } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'ChartRainFlow',
  props: {
     // props.data 的格式
    // {
    //   time: item.time,
    //   value: item.rain,  // 降雨
    //   value2: item.QSim, // 径流
    //   isWarmUp: item.isWarmUp
    // }
    data: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'editer'
    },
    startTime: {
      type: String,
      default: ''
    }
  },
  emits: ['update:data', 'data-change'],
  setup(props, { emit }) {
    const localData = ref([])
    const chartInstance = shallowRef(null)
    const chartContainer = ref(null)

    // 初始化数据
    const initData = () => {
       if (props.data && props.data.length > 0) {
        // 从props初始化数据
        localData.value = JSON.parse(JSON.stringify(props.data))
      }
      nextTick(() => {
        console.log('初始化预报结果图表', props.type, props.data.length)
        initChart()
      })
    }

    // 格式化时间
    const formatTime = (item) => {
      const date = new Date(item.time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:00`
    }

    // 初始化图表
    const initChart = () => {
      nextTick(() => {
        // 在Vue 3中使用正确的方式获取canvas
        const canvas = document.getElementById(`rainAndFlowChart-${props.type}`)
        if (!canvas) {
          console.error('未找到canvas元素')
          return
        }
        
        // 获取canvas容器尺寸
        const rect = canvas.getBoundingClientRect()
        if (!rect) {
          console.error('无法获取canvas尺寸')
          return
        }
        
        // 确保canvas有正确的尺寸
        canvas.width = rect.width
        canvas.height = rect.height
        
        // 重新初始化图表实例
        if (chartInstance.value) {
          chartInstance.value.dispose()
        }
        
        chartInstance.value = echarts.init(canvas)      
        updateChart()

        // 点击图表数据点编辑
        chartInstance.value.on('click', (params) => {
          if (params.componentType === 'series') {
            const index = params.dataIndex
            uni.showModal({
              title: `编辑 ${formatTime(localData.value[index])}`,
              editable: true,
              placeholderText: localData.value[index].value.toFixed(1),
              success: (res) => {
                if (res.confirm && res.content) {
                  localData.value[index].value = parseFloat(res.content) || 0
                  updateChart()
                  handleDataChange()
                }
              }
            })
          }
        })
      })
    }

    // 更新图表
    const updateChart = () => {
      if (!chartInstance.value) return

      // 计算开始时间索引（预热期结束、预见期开始的位置）
      let startTimeIndex = 0
      if (props.startTime && localData.value.length > 0) {
        const startTimeMs = new Date(props.startTime).getTime()
        startTimeIndex = localData.value.findIndex(item => {
          const itemTimeMs = new Date(item.time).getTime()
          return itemTimeMs >= startTimeMs
        })
        if (startTimeIndex === -1) startTimeIndex = localData.value.length - 1
      }

      const option = {
        title: {
          text: '降雨趋势',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: '600',
            color: '#2c3e50'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#409eff',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: 13
          },
          formatter: (params) => {
            const item = localData.value[params[0].dataIndex]
            const date = new Date(item.time)
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hour = String(date.getHours()).padStart(2, '0')
            const dateStr = `${month}-${day} ${hour}:00`
            const isWarmup = item.isWarmUp || (props.startTime && new Date(item.time).getTime() < new Date(props.startTime).getTime())
            const periodType = isWarmup ? '预热期' : '预见期'
            const periodColor = isWarmup ? '#95a5a6' : '#409eff'
            return`<div style="padding: 5px;">
              <div style="font-weight: bold; margin-bottom: 5px;">${dateStr}</div>
              <div style="margin-top: 3px; color: ${periodColor}; font-size: 12px;">${periodType}</div>
              <div style="margin-top: 5px; color: ${periodColor}; font-size: 16px; font-weight: bold;">降雨量: ${item.value.toFixed(1)} mm</div>
              <div style="margin-top: 5px; color: ${periodColor}; font-size: 16px; font-weight: bold;">径流: ${(item.value2 || 0).toFixed(1)} m³/s</div>
            </div>`
          },
        },
        grid: [{
          left: '50',
          right: '30',
          top: '80',
          height: '30%',
          containLabel: false
        }, {
          left: '50',
          right: '30',
          bottom: '90',
          top: '50%',
          height: '35%',
          containLabel: false
        }],
        legend: {
          data: ['降雨量', '径流'],  // 修改为径流
          left: 10
        },
        axisPointer: {
          link: [{ xAxisIndex: 'all' }]
        },
        xAxis: [{
          type: 'category',
          gridIndex: 0,  // 明确指定在上图
          position: 'top',
          data: localData.value.map((item, index) => index),
          nameLocation: 'middle',
          nameGap: 35,
          nameTextStyle: {
            fontSize: 13,
            color: '#666',
            fontWeight: 'bold'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            show: false  // 隐藏上图的X轴标签，避免遮挡数字
          }
        }, {
          type: 'category',
          gridIndex: 1,
          data: localData.value.map((item, index) => index),
          name: '时间',
          nameLocation: 'middle',
          nameGap: 35,
          nameTextStyle: {
            fontSize: 13,
            color: '#666',
            fontWeight: 'bold'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: '#ddd'
            }
          },
            axisLabel: {
              interval: (index) => {
                // 动态调整显示密度：根据数据量调整间隔
                const dataLength = localData.value.length
                if (dataLength > 200) return index % 30 === 0
                if (dataLength > 100) return index % 15 === 0
                if (dataLength > 50) return index % 8 === 0
                return index % 4 === 0
              },
              rotate: 45,
              fontSize: 10,
              color: '#666',
              formatter: (value) => {
                const item = localData.value[value]
                if (!item) return ''
                
                const date = new Date(item.time)
                const month = date.getMonth() + 1
                const day = date.getDate()
                const hour = String(date.getHours()).padStart(2, '0')
                
                return `${month}/${day} ${hour}:00`
              }
            }
        }],
        yAxis: [{
          inverse: true,  // 降雨倒着显示
          type: 'value',
          name: '',  // 不显示名称
          gridIndex: 0,  // 明确指定在上图
          nameTextStyle: {
            fontSize: 13,
            color: '#666',
            fontWeight: 'bold',
            padding: [0, 0, 0, 10]
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            fontSize: 12,
            color: '#666',
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          }
        }, {
          type: 'value',
          name: '',  // 不显示名称
          gridIndex: 1,  // 明确指定在下图
          nameTextStyle: {
            fontSize: 13,
            color: '#666',
            fontWeight: 'bold',
            padding: [0, 0, 0, 10]
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            fontSize: 12,
            color: '#666',
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          }
        }],
        series: [
          {
            name: '降雨量',
            type: 'bar',
            xAxisIndex: 0,
            yAxisIndex: 0,
            data: localData.value.map(item => item.value),
            barWidth: '60%',
            itemStyle: {
              color: (params) => {
                const item = localData.value[params.dataIndex]
                const value = params.value
                
                // 判断是预热期还是预见期
                const isWarmup = props.startTime && new Date(item.time).getTime() < new Date(props.startTime).getTime()
                
                if (isWarmup) {
                  // 预热期：灰色系
                  if (value === 0) return '#ecf0f1'
                  if (value < 1) return '#bdc3c7'
                  if (value < 5) return '#95a5a6'
                  if (value < 10) return '#7f8c8d'
                  return '#5d6d7e'
                } else {
                  // 预见期：蓝色系
                  if (value === 0) return '#e3f2fd'
                  if (value < 1) return '#90caf9'
                  if (value < 5) return '#42a5f5'
                  if (value < 10) return '#1e88e5'
                  return '#1565c0'
                }
              },
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                color: '#ff9800',
                shadowBlur: 10,
                shadowColor: 'rgba(255, 152, 0, 0.5)'
              }
            },
            label: {
              show: true,
              position: 'top',
              fontSize: 10,
              color: '#666',
              formatter: (params) => {
                return params.value > 0 ? params.value.toFixed(1) : ''
              }
            },
            markLine: {
              silent: true,
              symbol: 'none',
              data: props.startTime ? [{
                xAxis: startTimeIndex,
                lineStyle: {
                  color: '#e74c3c',
                  width: 2,
                  type: 'solid'
                },
                label: {
                  show: true,
                  position: 'insideEndTop',
                  formatter: '预报开始时间',
                  color: '#e74c3c',
                  fontSize: 12,
                  fontWeight: 'bold'
                }
              }] : []
            }
          }, {
            name: '径流',  // 修改为径流
            type: 'line',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: localData.value.map(item => item.value2 || 0),  // 使用 value2 (QSim)
            emphasis: {
              itemStyle: {
                color: '#ff9800',
                shadowBlur: 10,
                shadowColor: 'rgba(255, 152, 0, 0.5)'
              }
            },
            label: {
              show: true,
              position: 'top',
              fontSize: 10,
              color: '#666',
              formatter: (params) => {
                return params.value > 0 ? params.value.toFixed(1) : ''
              }
            },
            markLine: {
              silent: true,
              symbol: 'none',
              data: props.startTime ? [{
                xAxis: startTimeIndex,
                lineStyle: {
                  color: '#e74c3c',
                  width: 2,
                  type: 'solid'
                },
                label: {
                  show: true,
                  position: 'insideEndTop',
                  formatter: '预报开始时间',
                  color: '#e74c3c',
                  fontSize: 12,
                  fontWeight: 'bold'
                }
              }] : []
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            start: 70,  // 默认显示最后30%的数据
            realtime: true,
            end: 100,
            xAxisIndex: [0, 1]
          },
          {
            type: 'slider',
            start: 70,  // 默认滑块在最右边
            realtime: true,
            end: 100,
            xAxisIndex: [0, 1],
            bottom: 10
          }
        ]
      }

      chartInstance.value.setOption(option, true)
    }

    const handleDataChange = () => {
      emit('update:data', JSON.parse(JSON.stringify(localData.value)))
      emit('data-change')
    }

    watch(() => props.data, (newData) => {
      if (newData && newData.length > 0) {
        localData.value = JSON.parse(JSON.stringify(newData))
        updateChart()
      }
    }, { deep: true })

    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        nextTick(() => {
        const canvas = document.getElementById(`rainAndFlowChart-${props.type}`)
        if (canvas) {
          const rect = canvas.getBoundingClientRect()
          canvas.width = rect.width
          canvas.height = rect.height
          chartInstance.value.resize()
        }
        })
      }
    }

    // ResizeObserver 监听容器大小变化
    let resizeObserver = null

    // 组件挂载时添加监听
    onMounted(() => {
      initData()
      
      // 监听window resize
      window.addEventListener('resize', handleResize)
      
      // 使用 ResizeObserver 监听 canvas 父容器的大小变化
      nextTick(() => {
        const canvas = document.getElementById(`rainAndFlowChart-${props.type}`)
        if (canvas && canvas.parentElement && window.ResizeObserver) {
          resizeObserver = new ResizeObserver(() => {
            handleResize()
          })
          resizeObserver.observe(canvas.parentElement)
        }
      })
    })

    // 组件卸载时移除监听
    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      
      if (resizeObserver) {
        resizeObserver.disconnect()
        resizeObserver = null
      }
      
      if (chartInstance.value) {
        chartInstance.value.dispose()
      }
    })

    return {
      localData,
      chartContainer,
      formatTime,
    }
  }
}
</script>

<style scoped>
.chart-container {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  overflow-x: auto;
}

.chart-canvas {
  width: 100%;
  height: 500px;
}
</style>

